package com.itheima.sh.consumer.web;

import com.itheima.sh.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;


@RestController
@RequestMapping("consumer")
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    DiscoveryClient discoveryClient;

   /* @GetMapping("{id}")
//    @HystrixCommand(fallbackMethod = "queryByIdFallback")
    public User queryById(@PathVariable("id") String id) {
        //这里的客户端名字不区分大小获取实例"user-service"
        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
        ServiceInstance serviceInstance = instances.get(0);
        String host = serviceInstance.getHost();//获取主机
        int port = serviceInstance.getPort();//获取端口
        //基于Ribbon负载均衡调用
        String url = serviceInstance.getUri().toString();//获取请求URL
        if ("itheima".equals(id)) {
            throw new RuntimeException("ithiema繁忙异常");
        }
        User forObject = restTemplate.getForObject(url + "/user/" + id, User.class);
        return forObject;

     *//*
        String url = "http://localhost:8081/user/"+username;
        *//**//*RestTemplate会向http://localhost:8081/user/itcast(itcast就是username也是id)地址发起请求，
        并且得到响应的JSON数据。然后会将JSON数据反序列化为Map类型。*//**//*
        Map userMap = restTemplate.getForObject(url, Map.class);
        System.out.println(userMap);*//*
    }*/
   @GetMapping("{id}")
//    @HystrixCommand(fallbackMethod = "queryByIdFallBack")
   @HystrixCommand(fallbackMethod = "queryByIdFallback")
   public User queryById(@PathVariable("id") String id){

      /* if("itheima".equals(id)){
           throw new RuntimeException("itheima太忙了");
       }*/
       User user = restTemplate.getForObject("http://user-service/user/"+id, User.class);
       return user;
   }

    public User queryByIdFallback(@PathVariable("id") String id) {
        User user = new User();
        user.setUsername(id);
        user.setName("-1  暂停服务");
        return user;
    }

}